// pages/index/index.js
import API from "../../api/index";
const app = getApp()
import {
  getDate,comptime,yesterday
} from '../../utils/common'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // navbarData:{
    //   showCapsule:1,//是否显示右上角图标 1表示显示 0表示不显示
    //   title:'',//同事名字
    //   logo:'',//同事头像
    //   userId:''//同事id
    // },
    userId:'',//同事id
    compare:false,//判断大于等于今天就能添加，查看，checkbox
    cause:'',
    yesterday:'',//昨天
    // circular:true,
    height:'',
    today: "",
    explain: '今日',
    explainShow: true,
    current: 1,
    date: '',
    //工作任务
    jobId:-1,//任务id
    list: [
      {
        id: 0,
        time: '',
        jobList: [],
        studyList: [],
    },
     {
        id: 0,
        time: '',
        jobList: [],
        studyList: [],
    },
    {
      id: 0,
      time: '',
      jobList: [],
      studyList: [],
  },
  ],
    remarkModal: false,//查看详情/增加备注弹出层状态
    remarkData:{},//详情请求回来的数据
    pitchIndex: '',//当前选中下标
    inpuValue: '',//备注input
    bindshowIndex: '',//滑动下标
    addData: {
      message:'',//备注
      updateId:'',//项目修改的id
      dataStart:0,//从第几条开始
      count:100,//显示条数
      create_time:'',//创建时间
      addStatus: false,//新增
      addValue: '',//input新增任务名称
      //新增-选择项目
      project: [],
      projectType: 0,//选择项目类型
      projectStatus: false,//选择项目弹出层
      projectIndex: -1,//选择项目选中的下标
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.setData({
    //   height: app.globalData.height*2+20,
    // })
    let date = getDate(2)
    this.setData({ date: date })
    this.setData({yesterday:yesterday()})
    //今天的时间
    var day2 = new Date();
    day2.setTime(day2.getTime());
    var s2 = day2.getFullYear() + "-" + (day2.getMonth() + 1) + "-" + day2.getDate();
    this.setData({
      today: s2
    })
    // this.getCurrent()
  },
  //编辑今天的任务title‘双向绑定’
  bindInput(e) {
    let val = e.currentTarget.dataset.val
    this.setData({
      ['remarkData.title']: e.detail.value
    })
  },
   //编辑今天的任务备注‘双向绑定’
   bindremarkInput(e) {
    let val = e.currentTarget.dataset.val
    this.setData({
      ['remarkData.remark']: e.detail.value
    })
  },
  //发布任务
  _newJob(){
    let {project,projectIndex,addValue,remarkData,message} = this.data.addData
    let obj = {
      project_id:project[projectIndex].id,
      title:addValue,
      remark:message
    }
    // if(this.data.date!=this.data.today){
      let replaceval = getDate(3,remarkData=='{}'||remarkData==undefined?this.data.addData.create_time:remarkData.create_time)
      obj.time = replaceval.replace(/-/g,'/')
    // }
    API.newJob(obj).then(res=>{
      this.setData({  ['addData.projectIndex']: -1, ['addData.message']: '', ['addData.addValue']: ''})
      this._getDayJob()
    })
  },
//选择项目列表
_projectList(){
  let {dataStart,count,projectType,project} = this.data.addData
  let obj = {
    start:dataStart,//从第几条开始
    count:count,//显示条数
    type:projectType==0?1:projectType==1?2:projectType,//项目类型：0-全部，1-工作项目，2-学习项目
    status:0,//状态：0-全部，1-未开始，2-已结束，3-进行中	
    is_select:true//true-选择项目，false-项目列表
  }
  API.projectList(obj).then(res=>{
      // console.log(res)
      this.setData({
        ['addData.project']:[...(dataStart == 0 ? [] : project),...res.data.items],
      })
  })
},

  bindKeyInput: function (e) {
    this.setData({
      inpuvalue: e.detail.value
    })
  },
  //修改状态
  updateStatus: function (e) {
    if(this.data.today==this.data.date){
      API.settingCheckbox(e.currentTarget.dataset.id).then(res=>{
        setTimeout(() => {
          this._getLastTime()
        }, 500);
      })
    }
  },
  //查看详情弹出层
  showDetail: function (e) {
    // debugger
    console.log("showDetail")
    if(this.data.userId==''){
      this._getjob(e.currentTarget.dataset.id)
      this.setData({ 
        remarkModal: true, 
        jobId:e.currentTarget.dataset.id
      })
    }
   
  },
  _getjob(id){
    API.getjob(id).then(res=>{
      this.setData({remarkData:res.data})
    })
  },
  //关闭详情弹出层
  onTogglePopup: function () {
    if(this.data.addData.updateStaus){
      this.setData({ ['addData.updateStaus']: false,['addData.message']: '',['addData.projectIndex']: -1 ,remarkData:{} })
    }
    this.setData({ remarkModal: false,inpuvalue:'',['addData.message']: '',remarkData:{}})
  },
  
  remarkSubmit(){
    let {id,project_id,title,description,remark} = this.data.remarkData
    let {updateId,updateStaus} = this.data.addData
    if(title!=''){
    API.setRemark(id,{
      project_id:updateId!=''?updateId:project_id,
      title:title,
      description:this.data.inpuvalue!=''?this.data.inpuvalue:description,
      remark:this.data.addData.message!=''?this.data.addData.message:remark
  }).then(res=>{
      setTimeout(() => {
        this._getLastTime()
        this.onTogglePopup()
        this.setData({ remarkModal: false,inpuvalue:'' })
      }, 500);
    })
  }
  },
  // // // // //
  //新增关闭弹出层
  addPopup: function () {
    this.setData({ ['addData.addStatus']: false, ['addData.addValue']:'', ['addData.projectIndex']: -1,['addData.message']: '' })
  },
  //新增开启弹出层
  addshow: function () {
    this._projectList()
    this.setData({ ['addData.addStatus']: true,['addData.addValue']:'',['addData.create_time']:getDate(3,this.data.today) })
  },
  //编辑选择项目弹出层
  updateshow(){
    if(this.data.compare=='true'){
      this._projectList()
      this.setData({remarkModal:false, ['addData.projectStatus']: true,['addData.updateStaus']: true })
    }
  },
  bindaddInput: function (e) {
    this.setData({
      ['addData.addValue']: e.detail.value
    })
  },
  bindaddMessage: function (e) {
    this.setData({
      ['addData.message']: e.detail.value
    })
  },

  //选择项目关闭弹出层
  projectPopup: function () {
      if(this.data.addData.updateStaus){
        this.setData({ ['addData.projectStatus']: false,['remarkModal']: true })
      }else{
        this.setData({ ['addData.projectStatus']: false,['addData.addStatus']: true })
      }
  },
  //选择项目开启弹出层
  projectshow: function () {
    this.setData({ ['addData.projectStatus']: true,['addData.addStatus']: false })
  },
  //选中项目
  determine: function (e) {
    if(this.data.addData.updateStaus){
      this.setData({
         ['addData.projectIndex']: e.detail.index ,
         ['addData.updateId']:this.data.addData.project[e.detail.index].id,
         ['remarkData.project']:this.data.addData.project[e.detail.index],
         remarkModal:true
        })
      this.setData({ ['addData.projectStatus']: false })
    }else{
    this.setData({ ['addData.projectIndex']: e.detail.index })
    this.projectPopup()
    }
  },
  //切换项目类型
  updatePIndex() {
    this.setData({ ['addData.projectType']: this.data.addData.projectType == 0 ? '1' : '0' })
    this._projectList()
  },
  //新增任务提交
  addSubmit(e) {
    //保存+：储存该条任务后再新建一个未填写的任务弹窗 存储：存储后关闭弹窗
    //1保存 2 存储
    if (this.data.addData.addValue != '' && this.data.addData.projectIndex > -1) {
      if (e.currentTarget.dataset.type == 1) {
        this._newJob()
      } else {
        this._newJob()
        this.addPopup()
      }
    }
  },
  // 上一页
  previous: function () {
    // console.info('获取上一页,先看看今天是什么时候', this.data.today)
    var day1 = new Date(this.data.today);
    day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000);
    var newToday = day1.getFullYear() + "-" + ((day1.getMonth() + 1).toString().length<2?('0'+(day1.getMonth() + 1)):day1.getMonth() + 1) + "-" +  (day1.getDate().toString().length<2?('0'+day1.getDate()):day1.getDate())
    this.setData({
      today: newToday
    })
    let s1 = new Date()
    var startDate = Date.parse(newToday);
    var endDate = Date.parse(s1);
    var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
    days = Math.floor(days)
    if (days == 1) {
      this.setData({
        explain: '昨日',
        explainShow: true
      })
    } else if (days == 0) {
      this.setData({
        explain: '今日',
        explainShow: true
      })
    } else if (days == -1) {
      this.setData({
        explain: '明日',
        explainShow: true
      })
    } else {
      this.setData({
        explain: '',
        explainShow: false
      })
    }
    this.setData({compare:comptime(this.data.date,this.data.today)})
    this.updateCause()
    this._getDayJob()
  },

  // 后一天
  next: function () {
    // console.info('获取后一天,先看看今天是什么时候', this.data.today)
    let current = this.data.current + 1
    for (var i = 0; i < this.data.list.length; i++) {
      if (current == this.data.list[i].id) {
        this.setData({
          today: this.data.list[i].time,
          current: current
        })
      }
    }
    var day3 = new Date(this.data.today);
    day3.setTime(day3.getTime() + 24 * 60 * 60 * 1000);
    var newToday = day3.getFullYear() + "-" + ((day3.getMonth() + 1).toString().length<2?('0'+(day3.getMonth() + 1)):day3.getMonth() + 1) + "-" +  (day3.getDate().toString().length<2?('0'+day3.getDate()):day3.getDate())
    this.setData({
      today: newToday
    })
    let s1 = new Date()
    var startDate = Date.parse(s1);
    var endDate = Date.parse(newToday);
    var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
    days = Math.ceil(days)
    if (days == 1) {
      this.setData({
        explain: '明日',
        explainShow: true
      })
    } else if (days == 0) {
      this.setData({
        explain: '今日',
        explainShow: true
      })
    } else if (days == -1) {
      this.setData({
        explain: '昨日',
        explainShow: true
      })
    } else {
      this.setData({
        explain: '',
        explainShow: false
      })
    }
    this.setData({compare:comptime(this.data.date,this.data.today)})
    this.updateCause()
    this._getDayJob()
  },
  updateCause(){
    API.getLastTime().then(res=>{
      if(res.data!=''){
        let v1 = res.data.replace('\/','-')
        let v2 = v1.replace('\/','-')
        this.setData({cause:v2})
      }else{
        this.setData({cause:''})
      }
    })
  },
  // 滑动页面改变日期
  swiperTab: function (e) {
    // for (var i = 0; i < this.data.list.length; i++) {
    //   if (e.detail.current == this.data.list[i].id) {
          if(e.detail.current==0){
            this.previous()
          }else if(e.detail.current==2){
            if(this.data.compare=='true' || this.data.cause!=this.data.today){
              this.next()
            }
          }

        this.setData({
          // today: this.data.list[i].time,
          current: 1
        })
    //   }
    // }
    
  },
  explain(){
    let s1 = new Date()
    var m = s1.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = s1.getDate();
    d = d < 10 ? ('0' + d) : d;
    s1 = s1.getFullYear() + '-' + m + '-' + d
    var startDate = Date.parse(s1);
    var endDate = Date.parse(this.data.today);
    var days = (endDate-startDate) / (1 * 24 * 60 * 60 * 1000);
    days = Math.round(days)
    if (days == 1) {
      this.setData({
        explain: '明日',
        explainShow: true
      })
    } else if (days == 0) {
      this.setData({
        explain: '今日',
        explainShow: true
      })
    } else if (days == -1) {
      this.setData({
        explain: '昨日',
        explainShow: true
      })
    } else {
      this.setData({
        explain: '',
        explainShow: false
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  _getunfinish(){
    API.getunfinish().then(res=>{
        // this.setData({['lists[0].count']:res.data.job_num})
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
          this.getTabBar().setData({
            ['list[0].count']: res.data.job_num,
            ['list[1].count']: res.data.my_num
          })
        }
    })
  },
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    this._getLastTime()
  },
  _getLastTime(){
    API.getLastTime().then(res=>{
      if(res.data!=''){
        let v1 = res.data.replace('\/','-')
        let v2 = v1.replace('\/','-')
        console.log('comptime(this.data.date,v2)'+comptime(v2,this.data.date)+''+v2)
        let comptimeval=comptime(this.data.date,v2)
        this.setData({today:comptimeval=="true"?this.data.date:v2,cause:v2})
      }else{
        this.setData({today:this.data.date})
        this.setData({cause:''})
      }
      this.setData({compare:comptime(this.data.date,this.data.today)})
      this.explain()
      this._getDayJob()
    })
    this._getunfinish()
  },
  _getDayJob(){
    this.setData({
      ['list[1].jobList']:{},
      ['list[1].studyList']:{}
    })
    let obj = {
      time:this.data.today.replace(/-/g,'/')
    }
    if(this.data.userId!=''){
      obj.user_id=this.data.userId
    }
    API.getDayJob(obj).then(res=>{
      this.setData({
        ['list[1].jobList']:res.data.work_list,
        ['list[1].studyList']:res.data.study_list
      })
      
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  nav(){
    this.setData({userId:'',['navbarData.userId']:'',['navbarData.logo']:'',['navbarData.title']:''})
    // wx.switchTab({
    //     url: '/pages/menu/index',
    //   })
    wx.redirectTo({
      url: '/pages/lichuan_team/index',
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})